<template>
	<view class="uni-file-picker__container">
		<view v-if="files.length < limit && !readonly" class="file-picker__box" :style="boxStyle">
			<view class="file-picker__box-content is-add" :style="borderStyle" @click="choose">
				<slot>
					<view class="icon-add"></view>
					<view class="icon-add rotate"></view>
				</slot>
			</view>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex'
import * as qiniu from 'qiniu-js'
	export default {
		name: "uploadImage",
		props: {
			fileData: {
				type: Array,
				default () {
					return []
				}
			},
			disabled:{
				type: Boolean,
				default: false
			},
			disablePreview: {
				type: Boolean,
				default: false
			},
			//限制
			limit: {
				type: [Number, String],
				default: 9
			},
			imageStyles: {
				type: Object,
				default () {
					return {
						width: 'auto',
						height: 'auto',
						border: {}
					}
				}
			},
			//删除按钮
			delIcon: {
				type: Boolean,
				default: true
			},
			//只读
			readonly:{
				type:Boolean,
				default:false
			},
			//返回类型
			returnType: {
				type: String,
				default: 'array'
			},
			// 文件类型筛选
			fileExtname: {
				type: [Array, String],
				default () {
					return []
				}
			},
		},
		computed: {
			...mapGetters(['siteinfo']),
			showType() {
				if (this.fileMediatype === 'image') {
					return this.mode
				}
				return 'list'
			},
			styles() {
				let styles = {
					width: 'auto',
					height: 'auto',
					border: {}
				}
				return Object.assign(styles, this.imageStyles)
			},
			boxStyle() {
				const {
					width = 'auto',
						height = 'auto'
				} = this.styles
				let obj = {}
				if (height === 'auto') {
					if (width !== 'auto') {
						obj.height = this.value2px(width)
						obj['padding-top'] = 0
					} else {
						obj.height = 0
					}
				} else {
					obj.height = this.value2px(height)
					obj['padding-top'] = 0
				}

				if (width === 'auto') {
					if (height !== 'auto') {
						obj.width = this.value2px(height)
					} else {
						obj.width = '33.3%'
					}
				} else {
					obj.width = this.value2px(width)
				}

				let classles = ''
				for(let i in obj){
					classles+= `${i}:${obj[i]};`
				}
				return classles
			},
			borderStyle() {
				let {
					border
				} = this.styles
				let obj = {}
				const widthDefaultValue = 1
				const radiusDefaultValue = 3
				if (typeof border === 'boolean') {
					obj.border = border ? '1px #eee solid' : 'none'
				} else {
					let width = (border && border.width) || widthDefaultValue
					width = this.value2px(width)
					let radius = (border && border.radius) || radiusDefaultValue
					radius = this.value2px(radius)
					obj = {
						'border-width': width,
						'border-style': (border && border.style) || 'solid',
						'border-color': (border && border.color) || '#eee',
						'border-radius': radius
					}
				}
				let classles = ''
				for(let i in obj){
					classles+= `${i}:${obj[i]};`
				}
				return classles
			}
		},
		data(){
			return{
				files:[],
				fileTypes:[],
				previewVideo:false,
				previewUrl:'',
				audioInfo:{}
			}
		},
		methods: {
			get_extname() {
				let fileExtname = this.fileExtname
				if (!Array.isArray(fileExtname)) {
					let extname = fileExtname.replace(/(\[|\])/g, '')
					return extname.split(',')
				} else {
					return fileExtname
				}
				return []
			},
			
			uploadFiles(item, index) {
				this.$emit("uploadFiles", item)
			},
			/**
			 * 选择文件
			 */
			choose() {
				if (this.disabled) return
				if (this.files.length >= Number(this.limit) && this.showType !== 'grid' && this.returnType === 'array') {
					uni.showToast({
						title: `您最多选择 ${this.limit} 个文件`,
						icon: 'none'
					})
					return
				}
				let _this = this
				uni.chooseFile({
					count:1,
					sourceType:['album','camera'],
					success:async (res)=>{
						let fileTyle = res.tempFiles[0].name.split('.')
						let fTyle = '.'+fileTyle[fileTyle.length-1]
						let allowType = this.get_extname()
						let isIn = allowType.findIndex(item=>item==fTyle)
						
						if(isIn==-1){
							uni.showToast({
								title:'仅支持 '+allowType+' 类型文件',
								icon:'none'
							})
							return
						}
                        console.log(res,'++++++')
						let imageObj  = {
							furl:res.tempFilePaths[0],
							progress:0,
							errMsg:'',
							type:res.tempFiles[0].type.split('/')[0]
						}
						this.audioInfo.name = res.tempFiles[0].name
						console.log('+++++',typeof(_this.files),_this.files,imageObj)
						_this.files.push(imageObj)
						let index = _this.files.length - 1
						this.uploadImgToQiniu(res.tempFiles,0,index)
					}
				})
				
			},
			checkType(val) {
				let type = val
				if (type.indexOf('.jpg') > -1 || type.indexOf('.jpeg') > -1 || type.indexOf('.png') > -1 || type.indexOf('.gif') > -1) {
					return 'image'
				}
				if (type.indexOf('.mp4') > -1 || type.indexOf('.AVI') > -1 || type.indexOf('.mov') > -1 || type.indexOf(
						'.rmvb') > -1 || type.indexOf('.FLV') > -1 || type.indexOf('.rm') > -1 || type.indexOf('.3GP') > -
					1) {
					return 'video'
				}else{
					return 'file'
				}
			},
			get_files_and_is_max(res, _extname){
				let filePaths = []
				let files = []
				if(!_extname || _extname.length === 0){
					return {
						filePaths,
						files
					}
				}
				res.tempFiles.forEach(v => {
					let fileFullName = get_file_ext(v.name)
					const extname = fileFullName.ext.toLowerCase()
					if (_extname.indexOf(extname) !== -1) {
						files.push(v)
						filePaths.push(v.path)
					}
				})
				if (files.length !== res.tempFiles.length) {
					uni.showToast({
						title: `当前选择了${res.tempFiles.length}个文件 ，${res.tempFiles.length - files.length} 个文件格式不正确`,
						icon: 'none',
						duration: 5000
					})
				}
				return {
					filePaths,
					files
				}
			},
			delFile(index) {
				this.files.splice(index, 1)
				this.$emit('update',this.files)
			},
			prviewImage(img, index,imgType) {
				if(imgType=='video'){
					// uni.showToast({
					// 	title:'不支持视频预览',
					// 	icon:'none'
					// })
					this.previewUrl = img.url
					this.previewVideo = true
					return
				}
				let urls = []
				if(Number(this.limit) === 1&&this.disablePreview&&!this.disabled){
					this.$emit("choose")
				}
				if(this.disablePreview) return
				this.files.forEach(i => {
					urls.push(i.url)
				})

				uni.previewImage({
					urls: urls,
					current: index
				});
			},
			value2px(value) {
				if (typeof value === 'number') {
					value += 'px'
				} else {
					if (value.indexOf('%') === -1) {
						value = value.indexOf('px') !== -1 ? value : value + 'px'
					}
				}
				return value
			},
			getVideoUrl(res) {
				let _this = this
				return new Promise((resolve, reject) => {
					var pic = imageObj.split(";base64,")[1] // 截取data:image/png;base64,之后的base64
					var url = _this.siteinfo.up_.zoneHost + "/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名
					var xhr = new XMLHttpRequest();
					var xhrget = new XMLHttpRequest();
					var obj;
					xhr.open("POST", url, true);
					xhr.setRequestHeader("Content-Type", "image/png");
					xhr.setRequestHeader("Authorization", 'UpToken ' + _this.siteinfo.up_.upload_token);
					xhr.send(pic);
					xhr.onreadystatechange = () => {
						if (xhr.readyState == 4) {
							let info = JSON.parse(xhr.responseText)
							// this.imgUrl = info.domain + info.key
							resolve(info)
						}
					}
				});
			},
			//上传图片到七牛
            uploadImgToQiniu (file, i, progressIndex) {
                let _this = this
                /*skd上传七牛*/
                let putExtra = {}
                let config = {
                    useCdnDomain:true,
                    uphost:_this.siteinfo.up_.zoneHost.slice(6,_this.siteinfo.up_.zoneHost.length)
                }
                let observer = {
                    next(res){
						_this.files[progressIndex].progress+=res.total.percent.toFixed(1)
                    },
                    error(err){
                       uni.showToast({
							title:'上传失败',
							icon:'none'
                       })
                        //上传失败
                    },
                    complete(res){
                        //上传成功...  (登录七牛账号，找到七牛给你的 URL地址) 和 data里面的key 拼接成图片下载地址
						console.log('上传结束',res)
						let type =  _this.checkType(res.key)
						_this.uploadImageBack(res,type,progressIndex)
                    }
                };
                var observable = qiniu.upload(file[i], file[i].name, _this.siteinfo.up_.upload_token, putExtra, config);
                observable.subscribe(observer);//上传开始
            },
			//上传成功回调
			uploadImageBack(file,fileType,index){
				console.log('回调')
				let imageObj = this.files[index]
				imageObj.url = file.host + file.key
				imageObj.name = this.audioInfo.name
				this.files[index] = imageObj
				this.$emit('update',this.files)
			},
			imgToBase64(url) {
				return new Promise((resolve, reject) => {
					const image = new Image()
					image.src = url
					image.onload = () => {
						const canvas = document.createElement('canvas')
						canvas.width = image.naturalWidth // 使用 naturalWidth 为了保证图片的清晰度
						canvas.height = image.naturalHeight
						canvas.style.width = `${canvas.width / window.devicePixelRatio}px`
						canvas.style.height = `${canvas.height / window.devicePixelRatio}px`
						const ctx = canvas.getContext('2d')
						if (!ctx) {
							return null
						}
						ctx.drawImage(image, 0, 0)
						const base64 = canvas.toDataURL('image/png')
						return resolve(base64)
					}
					image.onerror = (err) => {
						return reject(err);
					}
				})
			},
		},
		mounted(){
			this.files = JSON.parse(JSON.stringify(this.fileData))
			this.files.map((item)=>{
				item.type = this.checkType(item.url)
			})
			console.log('++++++++++++++++++++fileExtname',this.fileExtname)
		},
		watch:{
			// fileData:{
			// 	handler(_n,_o){
			// 		this.files = _n
			// 	},immediate:true
			// }
		}
	}
</script>

<style lang="scss" scoped>
	.previewVideo{
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background: rgba(0,0,0,0.7);
		z-index: 99;
		.video{
			width: 100%;
			position: relative;
			top: 50%;
			transform: translateY(-50%);
		}
		.close{
			width: 70rpx;
			height: 70rpx;
			position: absolute;
			top: 80rpx;
			right: 50rpx;
			
		}
	}
	.uni-file-picker__container {
		/* #ifndef APP-NVUE */
		display: flex;
		box-sizing: border-box;
		/* #endif */
		flex-wrap: wrap;
		margin: -5px;
	}

	.file-picker__box {
		position: relative;
		// flex: 0 0 33.3%;
		width: 33.3%;
		height: 0;
		padding-top: 33.33%;
		/* #ifndef APP-NVUE */
		box-sizing: border-box;
		/* #endif */
	}

	.file-picker__box-content {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		margin: 5px;
		border: 1px #eee solid;
		border-radius: 5px;
		overflow: hidden;
	}

	.file-picker__progress {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		text-align: center;
		background-color: rgba(0,0,0,0.5);
		color: #fff;
		span{
			font-size: 24rpx;
			display: block;
			margin-bottom: 8rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
		}
		
		/* border: 1px red solid; */
		z-index: 2;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		align-items: center;
	}

	.file-picker__progress-item {
		width: 100%;
		margin-bottom: 18rpx;
	}

	.file-picker__mask {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		left: 0;
		color: #fff;
		font-size: 12px;
		background-color: rgba(0, 0, 0, 0.4);
	}

	.file-image {
		width: 100%;
		height: 100%;
	}
	._v{
		// display: flex;
		// justify-content: center;
		// align-items: center;
		position: relative;
		.icon{
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);
			z-index: 9;
		}
	}

	.is-add {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		align-items: center;
		justify-content: center;
	}

	.icon-add {
		width: 50px;
		height: 5px;
		background-color: #f1f1f1;
		border-radius: 2px;
	}

	.rotate {
		position: absolute;
		transform: rotate(90deg);
	}

	.icon-del-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		align-items: center;
		justify-content: center;
		position: absolute;
		top: 3px;
		right: 3px;
		height: 26px;
		width: 26px;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 2;
		transform: rotate(-45deg);
	}

	.icon-del {
		width: 15px;
		height: 2px;
		background-color: #fff;
		border-radius: 2px;
	}
</style>
